// Package system
// @Author zhongxc
// @Date 2024/7/25 14:59:00
// @Desc
package system

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"net/http"
	"strconv"
	"strings"
	"time"
	"vben-api/api/rpc"
	"vben-api/api/types"
	"vben-api/pkg/svc"
	common "vben-common"
	"vben-common/errs"
	"vben-common/utils"
	userServiceV1 "vben-grpc-common/vben-admin/types/user.service.v1"
)

type User struct {
	svcCtx *svc.ServiceContext
}

func NewUser(svcCtx *svc.ServiceContext) *User {
	return &User{
		svcCtx: svcCtx,
	}
}

// GetUserInfo
// @Description: 获取用户详情
// @receiver u
// @param c
func (u *User) GetUserInfo(c *gin.Context) {
	result := common.NewResult()
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, result.Fail(400, "参数错误"))
	}

	userReq := &userServiceV1.GetUserRequest{
		Id: id,
	}

	info, err := rpc.UserServiceClient.GetUserInfo(context.Background(), userReq)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}

	var userEntity types.UserEntity
	_ = copier.Copy(&userEntity, info)

	c.JSON(http.StatusOK, result.Success(userEntity))
}

// GetUserList
// @Description: 用户列表
// @receiver u
// @param c
func (u *User) GetUserList(c *gin.Context) {
	r := common.NewResult()
	// 参数获取
	page, err := strconv.ParseInt(c.DefaultQuery("page", "1"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "页码错误"))
		return
	}
	pageSize, err := strconv.ParseInt(c.DefaultQuery("pageSize", "10"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "limit参数错误"))
		return
	}

	status, err := strconv.ParseInt(c.DefaultQuery("status", "-1"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "参数错误"))
		return
	}

	deptId, err := strconv.ParseInt(c.DefaultQuery("deptId", "-1"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "deptId参数错误"))
		return
	}
	req := &userServiceV1.UserListRequest{
		Username: c.Query("userName"),
		Status:   int32(status),
		Page:     page,
		PageSize: pageSize,
		DeptId:   deptId,
	}
	list, err := rpc.UserServiceClient.GetUserList(context.Background(), req)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, r.Fail(code, msg))
		return
	}

	var userEntity = make([]*types.UserEntity, 0)
	for _, item := range list.Data {
		var user types.UserEntity
		_ = copier.Copy(&user, item)
		userEntity = append(userEntity, &user)
	}

	resultMap := map[string]interface{}{
		"page":      list.Page,
		"pageSize":  list.Limit,
		"totalPage": list.TotalPage,
		"total":     list.TotalCount,
		"items":     userEntity,
	}

	c.JSON(http.StatusOK, r.Success(resultMap))
}

func (u *User) SaveUser(c *gin.Context) {
	r := common.NewResult()
	// 获取参数
	var userEntity *types.UserEntity
	if err := c.ShouldBind(&userEntity); err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "参数错误"))
		return
	}
	var in userServiceV1.CreateUserRequest
	_ = copier.Copy(&in, userEntity)
	in.CreatedBy = "Kkk"
	in.Password = "123456"

	res, err := rpc.UserServiceClient.CreateUser(context.Background(), &in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, common.NewResult().Fail(code, msg))
		return
	}

	c.JSON(http.StatusOK, common.NewResult().Success(res))
}

// UpdateUser
// @Description: 用户信息更新
// @receiver u
// @param c
func (u *User) UpdateUser(c *gin.Context) {
	r := common.NewResult()
	// 参数获取
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "参数错误"))
		return
	}

	var userEntity *types.UserEntity
	if err := c.ShouldBind(&userEntity); err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "参数错误"))
		return
	}

	var in userServiceV1.UpdateUserRequest
	_ = copier.Copy(&in, userEntity)
	in.Id = id
	in.UpdatedBy = "Kkk"

	res, err := rpc.UserServiceClient.UpdateUser(context.Background(), &in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, r.Fail(code, msg))
		return
	}

	c.JSON(http.StatusOK, r.Success(res))
}

func (u *User) DeleteUser(c *gin.Context) {
	r := common.NewResult()
	// 参数获取
	ids := c.PostForm("ids")
	idArr := strings.Split(ids, ",")
	fmt.Printf("ids=%s\n", idArr)
	idSlice, err := utils.StringSliceToIntSlice(idArr)
	if err != nil {
		c.JSON(http.StatusOK, r.Fail(400, "参数错误"))
		return
	}

	var in userServiceV1.DeleteUserRequest
	in.Ids = idSlice
	in.DeletedBy = "Kkk"

	ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()

	res, err := rpc.UserServiceClient.DeleteUser(ctx, &in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, r.Fail(code, msg))
		return
	}
	c.JSON(http.StatusOK, r.Success(res))
}

func (u *User) ChangePassword(c *gin.Context) {
	r := common.NewResult()
	userName := c.PostForm("username")
	passOld := c.PostForm("passwordOld")
	passNew := c.PostForm("passwordNew")
	passConfirm := c.PostForm("passwordConfirm")

	in := &userServiceV1.ChangePasswordRequest{
		UserName:        userName,
		OldPassword:     passOld,
		NewPassword:     passNew,
		ConfirmPassword: passConfirm,
	}

	ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()
	res, err := rpc.UserServiceClient.ChangePassword(ctx, in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, r.Fail(code, msg))
		return
	}

	c.JSON(http.StatusOK, r.Success(res))
}
